<!-- 封装的echarts组件，能自定义样式，自适应窗口，异步修改数据 -->
<!--参考 https://blog.csdn.net/weixin_42775304/article/details/130390065 -->
<!-- 此模块的组件用例待ace-admin完成后再完善 -->
<template>
  <div ref="main" :style="style" v-loading="!myChart"/>
</template>

<script lang="ts" setup name="ComECharts">
import { nextTick } from 'vue'
import { onMounted, onBeforeUnmount, watch, ref, onDeactivated } from "vue";
import echarts from '@/utils/echarts/index';
// import * as echarts from 'echarts';

const main = ref()
const props = defineProps({
  style: {
    default: {
      width: '100%',
      height: '100%'
    }
  },
  option: {
    default: {},
  },reset:{
    default:false
  }
})

let myChart: echarts.ECharts;
//设置防抖，保证无论拖动窗口大小，只执行一次获取浏览器宽高的方法
const debounce = (fun: Function, delay: number | undefined) => {
  let timer: number | undefined;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    //写window目的是防止timer的ts报错，window.setTimeout返回的就直接是Nummber类型
    timer = window.setTimeout(() => {
      fun();
    }, delay);
  }
};
//重绘图表函数
const resizeHandler = () => {
  myChart?.resize();
}
//自适应函数与防抖结合，单独赋值是为了dom2能解绑事件
const cancalDebounce = debounce(resizeHandler, 50);

//页面挂载后，初始化echarts
onMounted(() => {
  //自适应不同屏幕时改变图表尺寸
  window.addEventListener('resize', cancalDebounce);
})
//页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', cancalDebounce)
  myChart.dispose()
})
// 防止 echarts 页面 keepAlive 时，还在继续监听页面
onDeactivated(() => {
  window.removeEventListener("resize", cancalDebounce);
});

//监听props变化，重新渲染图表
watch(props, async () => {
  await nextTick()
  myChart = echarts.init(main.value)
  myChart.setOption(props.option,props.reset)//reset为true时，表示每次重新渲染option，不与之前的option产生联系
  resizeHandler()
}, { deep: true })
</script>
  
  